import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../../core/api.service';
import { NzMessageService, NzModalService, UploadXHRArgs } from 'ng-zorro-antd';
import { environment } from '../../../../environments/environment';
import { ActivatedRoute, Params } from '@angular/router';
import { ReuseTabService } from '@delon/abc';
import { HttpEvent, HttpEventType, HttpRequest, HttpResponse, HttpClient } from '@angular/common/http';
import { ArticleManegeService } from './articleManege.service';
import { DatePipe } from '@angular/common';

@Component({
    selector: 'app-articlemanege',
    templateUrl: './articleManege.component.html',
    styleUrls: [
        './articleManege.component.less',
    ],
})

export class ArticleManegeComponent implements OnInit {
    editorConfig = {
        language: 'zh_CN',
        language_url: './assets/tinymce/langs/zh_CN.js',
        base_url: environment.outLink + '/tinymce',
        suffix: '.min',
        height: '60vh',
    };
    tableData: any[] = [];
    mapOfCheckedId = {};
    pagination: any = {
        pageSize: '50',
        pageNo: 1,
        totalNum: 0
    };
    addVisible: boolean;
    addData: any = {};
    editData: any = {};
    queryData: any = {};
    file: any = {};
    fileList: any[] = [];
    id = '';
    category = '';
    categoryNodes: any[] = [];
    workOrgNodes: any[] = [];
    dropdownStyle = {
        height: '200px',
        width: '200px',
    };
    editVisible: boolean;
    allCheck = false;
    lockHeadScroll = { y: window.innerHeight - 300 + 'px' };
    upload = environment.apiBase + '/csmis/news/upload.jwt';

    constructor(
        private http: HttpClient,
        private message: NzMessageService,
        private articleManegeService: ArticleManegeService,
        private activatedRoute: ActivatedRoute,
        private reuseTabService: ReuseTabService,
        private datePipe: DatePipe,
        public apiService: ApiService,
        private modalService: NzModalService,
    ) { }

    ngOnInit(): void {
        this.activatedRoute.params.subscribe((params: Params) => {
            const title = '文章管理';
            this.category = params.category;
            switch (this.category) {
                case 'tongzhilan':
                    this.reuseTabService.title = '通知公告';
                    break;
                case 'xuexijiaoliu':
                    this.reuseTabService.title = '学习园地';
                    break;
                case 'quntuangongzuo':
                    this.reuseTabService.title = '群团工作';
                    break;
                default:
                    this.reuseTabService.title = title;
                    break;
            }
            this.initCategory();
            this.initBm();
            this.loadData();
        });
    }

    initCategory() {
        this.articleManegeService.getCategory(this.category).subscribe(res => {
            this.categoryNodes = res;
            this.categoryNodes.unshift({
                vcName: '全部',
                vcID: '',
            });
        });
    }
    initBm() {
        this.apiService.departmentsPublicTree().subscribe(res => {
            this.workOrgNodes = res;
        });
    }

    getTreeNodeName(id, nodes) {
        for (const item of nodes) {
            if (item.key === id) {
                return item.title;
            } else if (item.children && item.children.length) {
                const name = this.getTreeNodeName(id, item.children);
                if (name) {
                    return name;
                }
            }
        }
    }

    checkAll(v) {
        this.tableData.forEach(row => {
            // this.mapOfCheckedId[row.id] = v;
            row.checked = v;
        });
    }

    loadData(_param?) {

        const param = {
            size: this.pagination.pageSize,
            pageNum: 1,
            mid: this.category
        };
        if (_param) {
            Object.assign(param, _param, this.queryData);
        }
        this.beforeQuery(param);
        this.articleManegeService.query(param).subscribe((res: any) => {
            if (res && res.data) {
                this.allCheck = false;
                this.tableData = res.data;
                this.pagination.totalNum = res.totalCount;
            }
        });
    }

    pageSizeChange(v) {
        this.loadData({
            size: v
        });
    }
    pageIndexChange(v) {
        this.loadData({
            pageNum: v
        });
    }

    resetVar() {
        const _date = new Date();
        this.fileList = [];
        this.file = {};
        this.addData = {
            _operDate: _date,
            _operTime: _date
        };
        this.editData = {
            _operDate: _date,
            _operTime: _date
        };
    }

    /**
     * 删除私立字段
     * @ param param
     */
    removePrivateFields(param) {
        Object.keys(param).forEach(key => {
            if (key.indexOf('_') === 0) {
                delete param[key];
            }
        });
    }
    /**
     * 删除后台不接受的字段
     * @ param param
     */
    removeUnacceptableFields(param) {
        Object.keys(param).forEach(key => {
            if (!param[key]) {
                delete param[key];
            }
        });
    }

    beforeQuery(data) {
        if (data._startDate) {
            data.startDate = this.datePipe.transform(new Date(data._startDate), 'yyyy-MM-dd');
        }
        if (data._endDate) {
            data.endDate = this.datePipe.transform(new Date(data._endDate), 'yyyy-MM-dd');
        }
        this.removePrivateFields(data);
        this.removeUnacceptableFields(data);
    }

    beforeSave(data) {
        if (data._operTime && data._operDate) {
            const time = this.datePipe.transform(new Date(data._operTime), 'HH:mm:ss');
            const _date = this.datePipe.transform(new Date(data._operDate), 'yyyy-MM-dd');
            data.operTime = _date + ' ' + time;
        }
        if (data.operOrgId) {
            data.operOrgName = this.getTreeNodeName(data.operOrgId, this.workOrgNodes);
        }
        data.fileUrl = this.file.fileUrl || "";
        data.fileName = this.file.fileName || "";
        this.removePrivateFields(data);
        this.removeUnacceptableFields(data);
    }

    beforeShow(data) {
        if (data.operTime) {
            data._operTime = new Date(data.operTime);
            data._operDate = data._operTime;
        }
        if (data.fileName) {
            this.fileList = [{
                // uid: 1,
                name: data.fileName,

            }];
        }
    }

    addModal() {
        this.addVisible = true;
        this.resetVar();
    }
    addCancel() {
        this.addVisible = false;
        this.resetVar();
    }

    acquiredCheck(param) {
        if (!param.category) {
            this.message.warning('请选择文章种类');
            return false;
        }
        if (!param.operOrgId) {
            this.message.warning('请选择文章来源');
            return false;
        }
        if (!param.title) {
            this.message.warning('请填写文章标题');
            return false;
        }
        if (param.title) {
            const title = param.title;
            if (title.indexOf('[') !== -1 || title.indexOf(']') !== -1) {
                this.message.warning('请把文章标题中的英文中括号（[]）改成中文中括号（【】）');
                return false;
            }
        }
        return true;
    }

    addOk() {
        const param = {};
        Object.assign(param, JSON.parse(JSON.stringify(this.addData)));
        this.beforeSave(param);
        if (!this.acquiredCheck(param)) {
            return;
        }
        this.articleManegeService.save(param).subscribe(res => {
            if (res && res.type === 'success') {
                this.message.success('新增成功');
                this.loadData({ pageNum: 1 });
                this.addVisible = false;
            } else {
                this.message.error(res.message);
            }
        });
    }

    editModal(id) {
        this.editVisible = true;
        this.resetVar();
        this.articleManegeService.getArticleInfo(id).subscribe(res => {
            Object.assign(this.editData, res);
            this.id = res.id;
            this.beforeShow(this.editData);
        });
    }

    editCancel() {
        this.editVisible = false;
        this.resetVar();
    }

    editOk() {
        const param: any = {};
        Object.assign(param, JSON.parse(JSON.stringify(this.editData)));
        this.beforeSave(param);
        if (!this.acquiredCheck(param)) {
            return;
        }
        if (!param.fileUrl) {
            this.modalService.confirm({
                nzTitle: '确认',
                nzContent: '您尚未上传附件，确定发布吗？',
                nzOkText: '确定',
                nzCancelText: '取消',
                nzOnOk: () => {
                    this.editNoCheck(param);
                }
            });
        } else {
            this.editNoCheck(param);
        }
    }

    editNoCheck(param) {
        this.articleManegeService.save(param).subscribe(res => {
            if (res && res.type === 'success') {
                this.message.success('保存成功');
                this.loadData({ pageNum: 1 });
                this.editVisible = false;
            } else {
                this.message.error(res.message);
            }
        });
    }

    getCheckIds() {
        const ids = [];
        this.tableData.forEach(row => {
            if (row.checked === true) {
                ids.push(row.id);
            }
        });
        return ids;
    }

    delete() {
        const ids = this.getCheckIds();
        if (!ids.length) {
            this.message.warning('请选择条目进行删除');
            return;
        }
        this.modalService.confirm({
            nzTitle: '确认',
            nzContent: '确定删除吗？',
            nzOkText: '确定',
            nzCancelText: '取消',
            nzOnOk: () => {
                this.articleManegeService.delete(`[${ids.join()}]`).subscribe(res => {
                    if (res.type === 'success') {
                        this.message.success('删除成功');
                        this.loadData();
                    } else {
                        this.message.error(res.message, { nzDuration: 5000 });
                    }
                });
            }
        });
    }

    deleteFile() {
        if (this.id) {
            this.articleManegeService.deleteFile(this.id).subscribe(res => {
                if (res.type === 'success') {
                    this.fileList = [];
                    this.file = {};
                    this.message.success('文件删除成功');
                    this.loadData();
                } else {
                    this.message.error(res.message);
                }
            });
        } else {
            this.fileList = [];
            this.file = {};
        }
    }

    checkUpload() {
        if (this.fileList.length) {
            this.message.info('请先删除原附件后再上传');
        }
    }

    uploadFileChange(type, e) {
        if (e.fileList) {
            this.fileList = e.fileList;
        }
        // if (e.file) {
        //     this.file = e.file;
        // }
        if (e.type === 'removed') {
            // const name = e;
            this.deleteFile();
        }
    }

    customReq = (item: UploadXHRArgs) => {
        // 构建一个 FormData 对象，用于存储文件或其他参数
        const formData = new FormData();
        formData.append('attachment', item.file as any);
        const req = new HttpRequest('POST', item.action, formData, {
            reportProgress: true,
            withCredentials: true
        });
        this.file = {};
        // 始终返回一个 `Subscription` 对象，nz-upload 会在适当时机自动取消订阅
        return this.http.request(req).subscribe((event: HttpEvent<{}>) => {
            if (event.type === HttpEventType.UploadProgress) {
                if (event.total > 0) {
                    (event as any).percent = event.loaded / event.total * 100;
                }
                // 处理上传进度条，必须指定 `percent` 属性来表示进度
                item.onProgress(event, item.file);
            } else if (event instanceof HttpResponse) {
                // 处理成功
                const res: any = event.body;
                this.file.fileName = res.fileName;
                this.file.fileUrl = res.fileUrl;
                item.onSuccess(event.body, item.file, event);
                this.message.success('上传成功');
            }
        }, (err) => {
            // 处理失败
            item.onError(err, item.file);
            this.message.error('上传过程发生异常！', { nzDuration: 1000 });
        });
    }

    formatHref(data) {
        return environment.apiBase + '/csmis/' + data.fileUrl;
    }

}
